package com.fjwt.gz.service.activity.platform.acte029;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 码上有福活动------
 */
@Slf4j
@Service
public class ACTE029Service extends BaseActivityService<Object> {

    private static String logPrefix = "【码上有福活动】";
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private AwardScoreService awardScoreService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private SendAwardService sendAwardService;

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE029的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE029的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE029的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE029的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }

    /**
     * 参与活动
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入:{},用户基本信息：{}", logPrefix, JSONUtil.toJsonStr(fansEntity));
        super.takePartIn(fansActivityDTO);
        Long fansId = fansActivityDTO.getFansId();
        String appId = fansActivityDTO.getAppId();
        Long activityId = fansActivityDTO.getActivityId();

        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        // 获取活动奖品
        List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(activityId, redisOutTime);
        log.info("活动奖品详细信息:{}", JSONUtil.toJsonStr(activityAwardList));
        if (CollUtil.isEmpty(activityAwardList)) {
            throw new BizException("该活动奖品已发放完毕");
        }

        // 校验用户奖品限制
        Map<Long, JSONObject> awardUserTimesJsonMap = new HashMap<>();
        for (ActivityAwardAndSettingBo activityAwardAndSettingBo : activityAwardList) {
            JSONObject awardUserTimesJson = awardSettingService.AwardSettingRule(fansId, activityEntity.getAgentNo(), activityAwardAndSettingBo);
            if (ObjectUtils.isNotEmpty(awardUserTimesJson)) {
                awardUserTimesJsonMap.put(activityAwardAndSettingBo.getAwardId(), awardUserTimesJson);
            }
        }

        for (ActivityAwardAndSettingBo awardAndSettingBo : activityAwardList) {
            sendAwardService.sendScore(fansId, appId, awardAndSettingBo, fansActivityDTO.getActivityChannelId(), true,
                    activityEntity.getAgentNo(), awardAndSettingBo.getAwardId(), Constants.SCORE.ACTIVITY);
            log.info("{}用户:{}增加{}福分", logPrefix, fansId, awardAndSettingBo.getScoreValue());
            JSONObject awardUserTimesJson = awardUserTimesJsonMap.get(awardAndSettingBo.getAwardId());
            awardSettingService.updateAwardLimitCache(awardUserTimesJson, redisOutTime);
        }
//        // 获取活动奖品ID
//        LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = ActivityAwardEntity.gw();
//        activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, activityId);
//        ActivityAwardEntity activityAwardEntity = activityAwardService.getOne(activityAwardWrapper);
//        // 获取奖品信息
//        AwardScoreEntity scoreAwardEntity = awardScoreService.getById(activityAwardEntity.getAwardId());
//        // 判断奖品是否发完
//        if (Objects.equals(scoreAwardEntity.getScoreGet(), scoreAwardEntity.getScoreNum())){
//            throw new BizException("当前活动已结束");
//        }
//        // 增加已领取数量
//        awardScoreService.update(new LambdaUpdateWrapper<AwardScoreEntity>()
//                .eq(AwardScoreEntity::getScoreId, scoreAwardEntity.getScoreId())
//                .setSql("score_get = score_get + 1"));

//        // 进行发积分处理
//        ScoreRecordTotalEntity scoreRecordTotalEntity = new ScoreRecordTotalEntity();
//        scoreRecordTotalEntity.setScore(scoreAwardEntity.getScoreValue());
//        scoreRecordTotalEntity.setName("码上有福得福分");
//        scoreRecordTotalEntity.setFlag(0);
//        scoreRecordTotalEntity.setInfoId(activityAwardEntity.getAwardId());
//        scoreRecordTotalEntity.setInfoType(Constants.SCORE.ACTIVITY);
//        scoreRecordTotalEntity.setAppId(fansActivityDTO.getAppId());
//        scoreRecordTotalEntity.setFansId(fansId);
//        scoreRecordTotalEntity.setActivityId(activityId);
//        scoreRecordTotalService.addScoreRecordTotal(activityEntity.getAgentNo(), scoreRecordTotalEntity, scoreAwardEntity.getOverDays(),
//                scoreAwardEntity.getOverType(),scoreAwardEntity.getOverTime());



//        ActivityAwardVO activityAwardVO = new ActivityAwardVO();
//        activityAwardVO.setAwardPrice(scoreAwardEntity.getScoreValue());

        //重新放置活动奖品配置缓存
        if (!activityAwardList.isEmpty()) {
            String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, fansActivityDTO.getActivityId(), Constants.REDIS_ACTIVITY.AWARD);
            RedisUtil.set(activityAwardKey, activityAwardList, redisOutTime, TimeUnit.MILLISECONDS);
            log.info("活动奖品列表，修改奖品中的当前周期性领取次数数据，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimes = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimes)){
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimes, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }
        return activityAwardService.toUserData(null);
    }
}
